<?php
namespace Admin\Model;
use Think\Model;
/**
 * 个人日程管理模型
 *
 */

class SourceModel extends Model{
	//添加日志接口
	public function add_source( $add_name, $add_info,$add_parent,$is_admin)
	{
		$r = array('d'=>NULL,'i'=>'','r'=>0,'s'=>'');
		$uinfo = $this->Guid();
		if( !$uinfo )
			$r['i'] = '加载用户信息失败';
			else{
				$d = array('name'=>$add_name,'create_time'=>date('Y-m-d H:i:s'),'remark'=>$add_info,'update_time'=>date('Y-m-d H:i:s'));

				if ($is_admin) {
				 	(!$add_parent) ? $d['sub_company'] = 1:$d['sub_company'] = $add_parent;
				}else{
					$useRec = D('Admin/User')->where('user_id='.$this->Guid())->find();
					$d['sub_company'] = $useRec['sector_id'];
				}
				$addID = $this->add( $d );
				if( $addID ){
					$r['r'] = $addID ;
					$r['i'] = 'OK';
					$r['d'] = $this->join('sector ON sector.sector_id = source.sub_company')->where( 'source_id='.$addID )->find();
				}else{
					$r['i'] = '保存失败';
				}
			}
		return $r;
	}

	//获取当前用户id
	public function Guid(){
		$uinfo = UserModel::loadFromSession();
		$userId = $uinfo['user_id'];
		return $userId;
	}
	// 渠道编辑
	public function channalEdit($id,$name,$parent,$info,$is_admin){
		$r = array('r'=>0,'m'=>'服务器忙，请稍候再试 return','data'=>NULL);
		$wheres = array('name'=>$name,'update_time'=>date('Y-m-d H:i:s'),'remark'=>$info);
		$arr = array();
		$editres = $this->where("source_id=".$id)->find();
		if (!$editres) {
			$r['m'] = "很抱歉，读取用户信息失败！";
			return $r;
		}
		if ($is_admin) {
			(!$parent)?$wheres['sub_company'] = 1:$wheres['sub_company'] = $parent;
		}else{
			$useRec = D('Admin/User')->where('user_id='.$this->Guid())->find();
			$wheres['sub_company'] = $useRec['sector_id'];
		}
		$editRtn = $this->where('source_id='.$id)->save($wheres);
		if ($editRtn) {
			$r['r'] = 1;
			$r['m'] = "用户编辑成功！";
			$r['data'] = $this->join('sector ON sector.sector_id = source.sub_company')->where("source_id=".$id)->find();
		}else{
			$r['m'] = "很抱歉，用户编辑失败！";
		}
		return $r;

	}

    //渠道删除
	public function delete_sou($id){
		$r = array('r'=>0,'i'=>'server error','d'=>NULL );
		$find = $this->where( array('source_id'=>array('eq',$id)) )->find();
		if( $find ){
			$res = M('customer')->where(array('source_id'=>$id))->count();
			if (!$res) {
				$r['r'] = 1;
				$r['i'] = 'OK';
			}else{
				$r['i'] = L('抱歉，这条渠道不能删除');
			}
		}
		else
			$r['i'] = L('渠道删除失败');
 		return $r;
	}
}
?>